// app/service/customer_service.js
'use strict';

const Service = require('egg').Service;

class CustomerService extends Service {
  // 获取客户列表
  async getCustomerList(page, pageSize, name) {
    const { ctx } = this;
    
    const query = {
      where: {}
    };
    
    if (name) {
      query.where.name = {
        [ctx.app.Sequelize.Op.like]: `%${name}%`
      };
    }
    
    const result = await ctx.model.CustomerModel.findAndCountAll({
      ...query,
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['created_at', 'DESC']]
    });
    
    return {
      list: result.rows,
      total: result.count
    };
  }
  
  // 根据ID获取客户
  async getCustomerById(id) {
    const { ctx } = this;
    return await ctx.model.CustomerModel.findByPk(id);
  }
  
  // 创建客户
  async createCustomer(customerData) {
    const { ctx } = this;
    return await ctx.model.CustomerModel.create(customerData);
  }
  
  // 更新客户
  async updateCustomer(id, customerData) {
    const { ctx } = this;
    const customer = await ctx.model.CustomerModel.findByPk(id);
    
    if (!customer) {
      throw new Error('客户不存在');
    }
    
    return await customer.update(customerData);
  }
  
  // 删除客户
  async deleteCustomer(id) {
    const { ctx } = this;
    const customer = await ctx.model.CustomerModel.findByPk(id);
    
    if (!customer) {
      throw new Error('客户不存在');
    }
    
    return await customer.destroy();
  }
}

module.exports = CustomerService;